/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.mango.android.chart;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.text.DecimalFormat;

import org.achartengine.chart.AbstractChart;
import org.achartengine.chart.ScatterChart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;
import org.achartengine.util.MathHelper;

import cc.mango.common.FinalKey;
import cc.mango.common.StringUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.activity.chart.NvChart;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.view.MotionEvent;
import static cc.mango.android.chartutil.ChartCommons.*;

/**
 * The XY chart rendering class.
 */
public class LineSmaChart extends UpLineChart
{

	protected float	smaLegendYLocation;

	protected float	smaTwoLegendXDistance;

	/**
	 * Builds a new XY chart instance.
	 * 
	 * @param dataset the multiple series dataset
	 * @param renderer the multiple series renderer
	 */
	public LineSmaChart(XYMultipleSeriesDataset dataset,
			XYMultipleSeriesRenderer renderer)
	{
		super(dataset, renderer);
		mDataset = dataset;
		mRenderer = renderer;
	}

	public LineSmaChart(XYMultipleSeriesDataset dataset,
			XYMultipleSeriesRenderer renderer, NvChart nvChart)
	{
		// TODO Auto-generated constructor stub
		super(dataset, renderer, nvChart);
		mDataset = dataset;
		mRenderer = renderer;
		this.nvChart = nvChart;

	}

	/**
	   * The graphical representation of the XY chart.
	   * 
	   * @param canvas the canvas to paint to
	   * @param x the top left x value of the view to draw to
	   * @param y the top left y value of the view to draw to
	   * @param width the width of the view to draw to
	   * @param height the height of the view to draw to
	   */
	@Override
	public void draw(Canvas canvas, int x, int y, int width, int height)
	{

		Paint paint = new Paint();
		paint.setAntiAlias(mRenderer.isAntialiasing());

		initSize(width, height);

		int left = x + leftWidth;
		int top = y + topHeight;
		int right = x + width - rightWidth;
		int bottom = y + height - bottomHeight;

		if (screenR == null)
		{
			screenR = new Rect();
		}
		screenR.set(left, top, right, bottom);

		//    canvas.drawRect(left, y, right, top, paint);//top

		drawTopBackground(mRenderer, canvas, left, y, right, top, paint);

		drawBackground(mRenderer, canvas, left, top, right - left, bottom
				- top, paint);//background

		drawBackgroundDottedLine(canvas, left, top, right - left, bottom
				- top, new Paint());

		if (paint.getTypeface() == null
				|| !paint.getTypeface().toString().equals(
						mRenderer.getTextTypefaceName())
				|| paint.getTypeface().getStyle() != mRenderer
						.getTextTypefaceStyle())
		{
			paint.setTypeface(Typeface.create(mRenderer
					.getTextTypefaceName(), mRenderer
					.getTextTypefaceStyle()));
		}
		Orientation or = mRenderer.getOrientation();

		double minX = mRenderer.getXAxisMin();
		double maxX = mRenderer.getXAxisMax();
		double minY = mRenderer.getYAxisMin();
		double maxY = mRenderer.getYAxisMax();
		boolean isMinXSet = mRenderer.isMinXSet();
		boolean isMaxXSet = mRenderer.isMaxXSet();
		boolean isMinYSet = mRenderer.isMinYSet();
		boolean isMaxYSet = mRenderer.isMaxYSet();
		//    double xPixelsPerUnit = 0;//by zhengan
		//    double yPixelsPerUnit = 0;//by zhengan
		int sLength = mDataset.getSeriesCount();
		String[] titles = new String[sLength];
		for (int i = 0; i < sLength; i++)
		{
			XYSeries series = mDataset.getSeriesAt(i);
			titles[i] = series.getTitle();
			if (series.getItemCount() == 0)
			{
				continue;
			}
			if (!isMinXSet)
			{
				double minimumX = series.getMinX();
				minX = Math.min(minX, minimumX);
				calcRange[0] = minX;
			}
			if (!isMaxXSet)
			{
				double maximumX = series.getMaxX();
				maxX = Math.max(maxX, maximumX);
				calcRange[1] = maxX;
			}

			//2年的MA数据前一段时间为0，是由于数据不足的问题，不用考虑
			double minimumY = series.getMinY();
			/*if(minimumY > 0){
			  
			  minY = Math.min(minY, (float) minimumY);
			  
			  calcRange[2] = minY;
			  
			  TDStockLog.d("Print_Info", "minY : "+minY);
			}*/
			minY = getMinY(minY, minimumY);

			double maximumY = series.getMaxY();
			maxY = Math.max(maxY, (float) maximumY);
			calcRange[3] = maxY;

		}

		if (maxX - minX != 0)
		{

			int count = this.mDataset.getSeriesAt(0).getItemCount();
			if (count == 0)
			{
				return;
			}
			xPixelsPerUnit = 1.0f * (right - left) / (count - 1);
		}
		/*    if (maxY - minY != 0) {
		      yPixelsPerUnit = (float) ((bottom - top) / (maxY - minY));
		    	
		    }*/

		if (!isEqual(maxY, minY))
		{
			yPixelsPerUnit = (float) ((bottom - top) / (maxY - minY));

		}

		boolean hasValues = true;//by zhengan

		/////////////by zhengan   调整了绘线的位置，调到了绘制坐标的后面

		//draw label and grid
		boolean showLabels = mRenderer.isShowLabels() && hasValues;
		boolean showGrid = mRenderer.isShowGrid();
		if (showLabels || showGrid)
		{

			if (showLabels)
			{
				paint.setColor(mRenderer.getLabelsColor());
				paint.setTextSize(mRenderer.getLabelsTextSize());
				paint.setTextAlign(Align.CENTER);//by zhengan origin

				drawXLabels(canvas, paint);

				drawYLabels(canvas, paint);

			}

		}

		//如果是一周的情况，在没有触摸的时候没有竖线
		if (getIsWeekChart() && !getIsTouching())
		{
			TDStockLog.d("Print_Info", "isWeekChart verticlaline");
			drawWeekChartVerticalLine(canvas, screenR.top, screenR.bottom,
					new Paint());
		}

		//draw series
		for (int i = 1; i < sLength; i++)
		{
			XYSeries series = mDataset.getSeriesAt(i);
			if (series.getItemCount() == 0)
			{
				continue;
			}
			hasValues = true;
			SimpleSeriesRenderer seriesRenderer = mRenderer
					.getSeriesRendererAt(i);

			int originalValuesLength = series.getItemCount();
			float[] points = null;
			int valuesLength = originalValuesLength;
			int length = valuesLength * 2;

			/////////////////////////////
			//去掉前一段为0的区域        	
			TDStockLog.d("Print_Info", "length:" + length);

			int k = 0;

			while (k < originalValuesLength && isEqual(series.getY(k), 0))
			{

				k += 1;
			}
			TDStockLog.d("Print_Info", "k:" + k);
			length = length - k * 2;
			TDStockLog.d("Print_Info", "length:" + length);

			if (length < 2)
			{
				continue;
			}

			points = new float[length];
			for (int j = 0; j < length; j += 2)
			{
				int index = j / 2 + k;
				//        points[j] = (float) (left + xPixelsPerUnit * (series.getX(index) - minX));
				points[j] = (float) (left + xPixelsPerUnit * index);
				points[j + 1] = (float) (bottom - yPixelsPerUnit
						* (series.getY(index) - minY) - 0.1f);
			}
			/////////////////////////////////

			drawSeries(canvas, paint, points, seriesRenderer, Math.min(
					bottom, (float) (bottom + yPixelsPerUnit * minY)), i);
			if (isRenderPoints(seriesRenderer))
			{
				ScatterChart pointsChart = new ScatterChart(mDataset,
						mRenderer);
				pointsChart.drawSeries(canvas, paint, points,
						seriesRenderer, 0, i);
			}
			paint.setTextSize(mRenderer.getChartValuesTextSize());
			if (or == Orientation.HORIZONTAL)
			{
				paint.setTextAlign(Align.CENTER);
			}
			else
			{
				paint.setTextAlign(Align.LEFT);
			}
			if (mRenderer.isDisplayChartValues())
			{
				drawChartValuesText(canvas, series, paint, points, i);
			}
		}

		//draw line  series//line 图要在下面
		for (int i = 0; i < 1; i++)
		{
			XYSeries series = mDataset.getSeriesAt(i);
			if (series.getItemCount() == 0)
			{
				continue;
			}
			hasValues = true;
			SimpleSeriesRenderer seriesRenderer = mRenderer
					.getSeriesRendererAt(i);

			int originalValuesLength = series.getItemCount();
			float[] points = null;
			int valuesLength = originalValuesLength;
			int length = valuesLength * 2;

			/////////////////////////////
			//去掉前一段为0的区域        	
			TDStockLog.d("Print_Info", "length:" + length);

			int k = 0;

			while (k < originalValuesLength && isEqual(series.getY(k), 0))
			{

				k += 1;
			}
			TDStockLog.d("Print_Info", "k:" + k);
			length = length - k * 2;
			TDStockLog.d("Print_Info", "length:" + length);

			if (length < 2)
			{
				continue;
			}

			points = new float[length];
			for (int j = 0; j < length; j += 2)
			{
				int index = j / 2 + k;
				//        points[j] = (float) (left + xPixelsPerUnit * (series.getX(index) - minX));
				points[j] = (float) (left + xPixelsPerUnit * index);
				points[j + 1] = (float) (bottom - yPixelsPerUnit
						* (series.getY(index) - minY));
			}
			/////////////////////////////////

			drawSeries(canvas, paint, points, seriesRenderer, Math.min(
					bottom, (float) (bottom + yPixelsPerUnit * minY)), i);
			if (isRenderPoints(seriesRenderer))
			{
				ScatterChart pointsChart = new ScatterChart(mDataset,
						mRenderer);
				pointsChart.drawSeries(canvas, paint, points,
						seriesRenderer, 0, i);
			}
			paint.setTextSize(mRenderer.getChartValuesTextSize());
			if (or == Orientation.HORIZONTAL)
			{
				paint.setTextAlign(Align.CENTER);
			}
			else
			{
				paint.setTextAlign(Align.LEFT);
			}
			if (mRenderer.isDisplayChartValues())
			{
				drawChartValuesText(canvas, series, paint, points, i);
			}
		}

		//draw Legend

		drawSmaLegend(canvas, paint);

		if (getIsTouching())
		{
			//    	float xLocation = (float) ((mDataset.getSeriesAt(0).getX(NvChart.index)-calcRange[0]) * xPixelsPerUnit);

			float xLocation = getXLocation(getIndex());

			TDStockLog.d("Print_Info", "xLocation:" + xLocation);

			drawVerticalLine(canvas, xLocation, top, bottom);

			drawCircle(canvas, xLocation, getYLocation(getIndex()));

			drawTopBm(canvas, getBmX(xLocation), y, bmWidth, topHeight,
					getYValue(getIndex()));

		}

	}

	private void drawSmaLegend(Canvas canvas, Paint paint)
	{

		paint = new Paint();

		paint.setAntiAlias(true);

		paint.setTextSize(mRenderer.getLegendTextSize());
		paint.setTypeface(Typeface.DEFAULT_BOLD);

		smaLegendYLocation = screenR.top - paint.ascent();

		smaTwoLegendXDistance = paint.measureText(MA50);

		SimpleSeriesRenderer seriesRenderer = mRenderer
				.getSeriesRendererAt(2);
		paint.setStrokeWidth(seriesRenderer.getColor());
		paint.setColor(seriesRenderer.getColor());
		//        paint.setStyle(Style.STROKE);
		paint.setTextAlign(Align.RIGHT);

		canvas.drawText(MA50, screenR.right, smaLegendYLocation, paint);

		seriesRenderer = mRenderer.getSeriesRendererAt(1);
		paint.setStrokeWidth(seriesRenderer.getColor());
		paint.setColor(seriesRenderer.getColor());
		//        paint.setStyle(Style.STROKE);
		paint.setTextAlign(Align.RIGHT);
		canvas.drawText(MA10, screenR.right - smaTwoLegendXDistance,
				smaLegendYLocation, paint);
	}

}
